<?php

namespace Litche\Tool;

class Tool
{
    static function test()
    {
        self::showMethods();
    }

    static function showMethods()
    {
        $json_string = file_get_contents(__DIR__ . '\methods.json');
        $methods = json_decode($json_string, true);
        $str = '<style>.b{font-weight: bold;color: #4c4c4c;}.b1,.b2{width: 150px;display: inline-block;}.br{display: block;}td{line-height: 28px;padding: 10px 13px;border: 1px solid #dfdfdf;}table th {padding: 10px 13px;border: 1px solid #dfdfdf;}</style>';
        $str .= '<table style="margin: 0 auto;" cellpadding="0" cellspacing="0">';
        $str .= '<thead>';
        $str .= '<tr style="background-color: #f2f2f2;height: 38px;"><th>No.</th><th width="300">方法名</th><th width="200">方法</th><th>注释</th></tr>';
        $str .= '</thead>';
        foreach ($methods as $k => $v) {
            //$v = explode(',','<br>',$v);
            $v['remarkMust'] = explode(',', $v['remarkMust']);
            $v['remarkNoMust'] = explode(',', $v['remarkNoMust']);
            $str .= '<tr>';
            $str .= '<td>' . $k . '</td>';
            $str .= '<td>' . $v['title'] . '</td>';
            $str .= '<td>' . $v['func'] . '</td>';
            $str .= '<td>';
            foreach ($v['remarkMust'] as $key => $val) {
                $val = explode(' ', $val);
                if (empty($val[1])) continue;
                $str .= "<span class='b1 b'>$val[1]</span>";
                $str .= "<span class='b2 b'>$val[0]</span>";
                $str .= "<span class='b'>$val[2]</span>";
                $str .= "<span class='br b'></span>";
            }
            foreach ($v['remarkNoMust'] as $key => $val) {
                $val = explode(' ', $val);
                if (empty($val[1])) continue;
                $str .= "<span class='b1'>$val[1]</span>";
                $str .= "<span class='b2'>$val[0]</span>";
                $str .= "<span>$val[2]</span>";
                $str .= "<span class='br'></span>";
            }
            $str .= '</td>';
            $str .= '</tr>';
        }
        $str .= '</table>';
        echo $str;
    }

    /*
     * 生成随机字符串*/
    static function generateRandomString($length = 10, $characters = '')
    {
        $characters = isset($characters) ? '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' : '';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

    //获取文件扩展名（后缀）
    static function getExt($filename)
    {
        $myext = substr($filename, strrpos($filename, '.'));
        return str_replace('.', '', $myext);
    }

    //字符串显示长度，超出使用...显示
    static function cutStr($string, $sublen, $start = 0, $code = 'UTF-8')
    {
        if ($code == 'UTF-8') {
            $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
            preg_match_all($pa, $string, $t_string);
            if (count($t_string[0]) - $start > $sublen) {
                return join('', array_slice($t_string[0], $start, $sublen)) . "...";
            }
            return join('', array_slice($t_string[0], $start, $sublen));
        } else {
            $start = $start * 2;
            $sublen = $sublen * 2;
            $strlen = strlen($string);
            $tmpstr = '';
            for ($i = 0; $i < $strlen; $i++) {
                if ($i >= $start && $i < ($start + $sublen)) {
                    if (ord(substr($string, $i, 1)) > 129) {
                        $tmpstr .= substr($string, $i, 2);
                    } else {
                        $tmpstr .= substr($string, $i, 1);
                    }
                }
                if (ord(substr($string, $i, 1)) > 129) {
                    $i++;
                }
            }
            if (strlen($tmpstr) < $strlen) $tmpstr .= "...";
            return $tmpstr;
        }
    }

    /**
     * xml转数组
     * @param $xml  需要转化的xml
     * @return mixed
     */
    function xml_to_array($xml)
    {
        $ob = simplexml_load_string($xml);
        $json = json_encode($ob);
        $array = json_decode($json, true);
        return $array;
    }


    /**
     * 数组转xml
     * @param $array 需要转化的数组
     * @return string
     */
    function array_to_xml($array)
    {
        if (is_object($array)) {
            $array = get_object_vars($array);
        }
        $xml = '';
        foreach ($array as $key => $val) {
            if (is_null($val)) {
                $xml .= "<$key/>\n";
            } else {
                if (!is_numeric($key)) {
                    $xml .= "<$key>";
                }
                $xml .= (is_array($val) || is_object($val)) ? self::data_to_xml($val) : $val;
                if (!is_numeric($key)) {
                    $xml .= "</$key>";
                }
            }
        }
        return $xml;
    }

    /**
     * 获取当前服务器系统
     * @return string
     */
    static function getOS()
    {
        if (PATH_SEPARATOR == ':') {
            return 'Linux';
        } else {
            return 'Windows';
        }
    }


    /**
     * 写日志
     * @param $log  日志内容
     * @param $dir  保存路径
     */
    static function log_write($log, $dir = '')
    {
        if (empty($dir)) {
            $dir = __DIR__ . "/../log/";
        }

        if (!is_dir($dir)) {
            mkdir($dir);
        }
        $filename = $dir . date("Y-m-d") . ".log";
        file_put_contents($filename, date("Y-m-d H:i:s") . "\t" . $log . PHP_EOL, FILE_APPEND);
    }


    /**
     * 二维数组跟据某个值排序
     * @param $array            排序的数组
     * @param $field            排序字集
     * @param string $sort 排序方式， SORT_ASC：升序排列，SORT_DESC：降序排列
     * @return mixed
     */
    static function arraySort($array, $field, $sort = 'ASC')
    {
        $sorts = array('ASC' => 'SORT_ASC', 'DESC' => 'SORT_DESC');
        $sort = $sorts[$sort];
        $arrSort = array();
        foreach ($array as $uniqid => $row) {
            foreach ($row as $key => $value) {
                $arrSort[$key][$uniqid] = $value;
            }
        }
        array_multisort($arrSort[$field], constant($sort), $array);
        return $array;
    }

    /**
     * 时间戳转多少时间前，如：30秒前
     * @param $time 时间戳
     * @return string
     */
    static function formatDate($time)
    {
        $t = time() - $time != 0 ? time() - $time : 1;
        $f = array(
            '31536000' => '年',
            '2592000' => '个月',
            '604800' => '星期',
            '86400' => '天',
            '3600' => '小时',
            '60' => '分钟',
            '1' => '秒'
        );
        foreach ($f as $k => $v) {
            if (0 != $c = floor($t / (int)$k)) {
                return $c . $v . '前';
            }
        }
    }

    /**
     * 把秒转换成时间
     * @param $time
     * @return bool|string
     */
    static function formatDate2($time)
    {
        if (is_numeric($time) && $time > 0) {
            $date = '';
            $value = array(
                "years" => 0, "days" => 0, "hours" => 0,
                "minutes" => 0, "seconds" => 0,
            );

            if ($time >= 31556926) {
                $value["years"] = floor($time / 31556926);
                $date .= $value["years"] . "年";
                $time = ($time % 31556926);
            }

            if ($time >= 86400) {
                $value["days"] = floor($time / 86400);
                $date .= $value["days"] . "天";
                $time = ($time % 86400);
            }

            if ($time >= 3600) {
                $value["hours"] = floor($time / 3600);
                $date .= $value["hours"] . "小时";
                $time = ($time % 3600);
            }

            if ($time >= 60) {
                $value["minutes"] = floor($time / 60);
                $date .= $value["minutes"] . "分";
                $time = ($time % 60);
            }

            $value["seconds"] = floor($time);
            $date .= $value["seconds"] . "秒";

            return $date;

        } else {
            return false;
        }
    }

    /**
     * 正则：手机号（精确）
     * <p>移动：134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188、198</p>
     * <p>联通：130、131、132、145、155、156、175、176、185、186、166</p>
     * <p>电信：133、153、173、177、180、181、189、199</p>
     * <p>全球星：1349</p>
     * <p>虚拟运营商：170</p>
     */
    static function is_mobile($mobile)
    {
        $search = '/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0-9])|(18[0-9])|166|198|199|(147))\\d{8}$/';
        if (preg_match($search, $mobile)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 毫秒级时间戳
     * @return float
     */
    static function timeMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }


    /*
     * 时间戳转日期
     * @param $time 时间戳
     * @param $type Int 日期位数
     * @return String 日期
     * */
    static function timetodate($time = 0, $type = 6)
    {
        $types = array('Y-m-d', 'Y', 'm-d', 'Y-m-d', 'm-d H:i', 'Y-m-d H:i', 'Y-m-d H:i:s');
        if (isset($types[$type])) $type = $types[$type];
        if ($time > 2147212800) {
            if (class_exists('DateTime')) {
                $D = new DateTime('@' . ($time - 3600 * intval(str_replace('Etc/GMT', '', $GLOBALS['CFG']['timezone']))));
                return $D->format($type);
            }
        }
        return date($type, $time);
    }

    /*
     * 日期转时间戳
     * @param $date 日期
     * @return Int 时间戳
     * */
    static function datetotime($date)
    {
        return strtotime(date($date));
    }

    /*
     * 验证是否是正确的邮箱
     * @param $email 邮箱地址
     * @return Boolean
     * */
    static function is_email($email)
    {
        $result = trim($email);
        if (filter_var($result, FILTER_VALIDATE_EMAIL)) {
            return true;
        } else {
            return false;
        }
    }

}